<template>
  <div class="add-alert-container">
    <h2 style="text-align: left;margin-left:3.5%; ">警报规则添加</h2>

    <el-form ref="form" :model="ruleForm" :rules="rules" label-width="100px" style="width:95%;">

      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item label="警报名" prop="alertname">
            <el-input v-model="ruleForm.alertname" @change="includeName" />
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item label="检测间隔" prop="intervalNum">
            <el-input v-model="ruleForm.intervalNum" style="width:100px" />
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-select v-model="ruleForm.intervalStr" style="width:100px">
            <el-option
              v-for="item in intervalStrArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>

        <el-col :span="3">
          <el-form-item label="检测时段" prop="durationNum">
            <el-input v-model="ruleForm.durationNum" style="width:100px" />
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-select
            v-model="ruleForm.durationStr"
            style="width:100px"
          >
            <el-option
              v-for="item in durationStrArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-form-item label="是否运行" prop="state">
            <el-select v-model="ruleForm.state" style="width:100%">
              <el-option value="true" label="是" />
              <el-option value="false" label="否" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-tooltip class="item" effect="dark" :content="levelShow" placement="top-end">
            <el-form-item label="警报等级" prop="level">
              <el-select v-model="ruleForm.level" style="width:100%">
                <el-option value="a" label="高" />
                <el-option value="b" label="中" />
                <el-option value="c" label="低" />
              </el-select>
            </el-form-item>
          </el-tooltip>
        </el-col>
      </el-row>

      <!-- <el-form-item style="font-weight: 600" label="条件：" /> -->

      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item label="metric" prop="metric">
            <el-select v-model="ruleForm.metric" style="width:100%" @change="metricChange">
              <el-option v-for="item in metricArr" :key="item" :value="item" :label="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="15" class="formCol">
          <!-- <label class="tagLabel">标签</label> -->
          <el-form-item label="标签">
            <div id="showTagsDiv2" class="tagDiv2" />
            <div v-show="isShow" id="tagSelectDiv" class="tagDiv2">
              <el-select v-model="Tags.tag_key" class="tagSelect2" size="small " placeholder="选择键" clearable filterable @change="tagKeyChange">
                <el-option v-for="(tag_key, i) in key_list" :key="i" :label="tag_key" :value="tag_key" />
              </el-select>
              <el-select v-model="Tags.tag_val" class="tagSelect2" size="small " placeholder="选择值" clearable filterable>
                <el-option v-for="(tag_val, j) in val_list" :key="j" :label="tag_val" :value="tag_val" />
              </el-select>
              <el-button type="infor" size="small " icon="el-icon-plus" @click="addTag">添加</el-button>
            </div>
            <el-button v-show="bottonShow" style=" margin-top: 7px; float:left;" type="success" size="small " icon="el-icon-plus" @click="addTagsInit" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item style="font-weight: 600" label="报警条件" prop="state">
            <el-input v-model="ruleForm.less" style="width:25%" prop="less" />
            <div style="width:5%;text-align: center;display:inline-block">≤</div>
            <el-select v-model="ruleForm.function" style="width:40%">
              <el-option
                v-for="item in functionArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <div style="width:5%;text-align: center;display:inline-block">≤</div>
            <el-input v-model="ruleForm.more" style="width:25%" prop="more" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="3">
        </el-col>
        <el-col :span="3">
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="描述" prop="description">
            <el-input v-model="ruleForm.description" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="提示信息" prop="content">
            <el-input v-model="ruleForm.content" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button style="float: right" type="primary" @click="submitAdd">添加规则</el-button>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
// import { getMetricList, getAlertNameList, addAlert } from '@/api/Alert.js'
// import axios from 'axios'
import axiosservice from '@/utils/CommonData.js'
// import { getMetricsState, getMetricsLocal, setMetrics } from '@/utils/CommonData.js'

export default {
  name: 'AddAlert',
  data() {
    var validateNum = (rule, value, callback) => {
      if (!this.ruleForm.more && !this.ruleForm.less) {
        callback(new Error('请至少填写一项'))
      } else {
        callback()
      }
    }
    return {
      metrictagstree: null,
      levelShow: '高:邮件提醒 中:消息提示 低:只记录',
      isShow: false,
      bottonShow: true,
      tagHtml: '',
      key_list: [],
      val_list: [],
      Form: {
        metric: '',
        tag: ''
      },
      Tags: {
        tag_key: '',
        tag_val: ''
      },
      ruleForm: {
        alertname: '测试警报1',
        description: '最小值大于11',
        metric: '',
        intervalNum: '10',
        intervalStr: 's',
        function: 'min',
        state: 'false',
        level: 'b',
        Symbol: 'more',
        durationNum: '20',
        durationStr: 's-ago',
        content: '发生警报,最小值大于11',
        less: '',
        more: '',
        filterValue: '11'
        // maximum: '',
        // minimum: '',
        // equal: ''
      },
      intervalStrArr: [{
        value: 's',
        label: '秒'
      }, {
        value: 'm',
        label: '分钟'
      }, {
        value: 'h',
        label: '小时'
      }],
      functionArr: [{
        value: 'max',
        label: '最大值'
      }, {
        value: 'min',
        label: '最小值'
      }, {
        value: 'sum',
        label: '求和'
      }, {
        value: 'count',
        label: '计数'
      }, {
        value: 'avg',
        label: '平均值'
      }],
      durationStrArr: [{
        value: 's-ago',
        label: '秒前'
      }, {
        value: 'm-ago',
        label: '分钟前'
      }, {
        value: 'h-ago',
        label: '小时前'
      }],
      metricArr: [],
      alertNameArr: [],
      rules: {
        alertname: [{ required: true, message: '请输入警报名' }],
        description: [{ required: true, message: '请输入描述' }],
        intervalNum: [{ required: true, message: '此为必填项' }],
        durationNum: [{ required: true, message: '此为必填项' }],
        metric: [{ required: true }],
        intervalStr: [{ required: true }],
        durationStr: [{ required: true }],
        more: [{ validator: validateNum, trigger: 'blur', message: '边界值至少填一个' }],
        less: [{ validator: validateNum, trigger: 'blur', message: '边界值至少填一个' }],
        state: [{ required: true }],
        level: [{ required: true }],
        content: [{ required: true, message: '请输入提示信息' }]
      }
    }
  },
  created() {
    const _this = this
    window.delTag = _this.delTag
  },
  mounted() {
    // if (getMetricsState()) {
    //   console.log('本地获取数据')
    //   this.metricArr = getMetricsLocal()
    // } else {
    //   console.log('网络请求数据')
    //   this.getMetricList()
    // }
    this.getMetricList()
    // this.metricArr = metricArr
    this.getAlertNameList()
    // this.getMetricTagTree()
    // this.getTagKeys()
    // this.getTagValues()
  },
  methods: {
    metricChange(metric) {
      console.log('metricChange', metric)
      this.key_list.splice(0)
      this.val_list = []
      if (this.metrictagstree[metric]) {
        for (var p1 in this.metrictagstree[metric]) {
          this.key_list.push(p1)
        }
      }
      console.log('key_list', this.key_list)
      this.Tags.tag_key = ''
      this.Tags.tag_val = ''
    },
    tagKeyChange(tagkey) {
      console.log('tagKeyChange', tagkey)
      this.val_list = this.metrictagstree[this.ruleForm.metric][tagkey]
      console.log('val_list', this.val_list)
      this.Tags.tag_val = ''
      console.log('this.Tags', this.Tags)
    },
    getMetricTagTree() {
      axiosservice({
        url: '/metrictagstree',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            if (res.data.code == 200) {
              this.metrictagstree = JSON.parse(res.data.data)
              this.metricChange(this.ruleForm.metric)
              // console.log('metrictagstree', this.metrictagstree)
              // for (var p1 in this.metrictagstree) {
              //   // this.metricArr.splice(0)
              //   this.metricArr.push(p1)
              // }
              // if (this.metricArr.length > 0) {
              //   this.ruleForm.metric = this.metricArr[0] // 默认值取第一个
              //   this.metricChange(this.ruleForm.metric)
              // }
              // console.log('metricArr', this.metricArr)
            }
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag数据失败!')
        })
    },
    addTagsInit() {
      this.isShow = true
      this.bottonShow = false
    },
    addTag() {
      // var id = this.Tags.tag_key + '_' + this.Tags.tag_val
      var text = this.Tags.tag_key + '=' + this.Tags.tag_val
      if (text == '=') {
        this.isShow = false
        this.bottonShow = true
        return
      }
      if (this.Form.tag == '') {
        this.Form.tag = text
      } else {
        this.Form.tag += ',' + text
      }
      this.tagHtml += '<label style="margin-left:5px;border: 1px solid #00557f;">' + text + '<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" onClick="delTag(\'' + text + '\')" ></i> </label>'// <button style="cursor:pointer;padding-left:5px;"  onClick="delTag(\''+text+'\')">'+text+'<i style="cursor:pointer;padding-left:5px;"  class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';
      this.isShow = false
      this.bottonShow = true
      var div = document.getElementById('showTagsDiv2')
      div.innerHTML = this.tagHtml
    },
    delTag(id) {
      var tag1 = this.Form.tag.replace(id + ',', '')
      var tag2 = this.Form.tag.replace(',' + id, '')
      if (this.Form.tag == tag1) {
        if (this.Form.tag == tag2) {
          this.Form.tag = this.Form.tag.replace(id, '')
        } else {
          this.Form.tag = this.Form.tag.replace(',' + id, '')
        }
      } else {
        this.Form.tag = this.Form.tag.replace(id + ',', '')
      }
      var delHtml = '<label style="margin-left:5px;border: 1px solid #00557f;">' + id + '<i style="cursor:pointer;padding-left:5px;" class="remove el-icon-remove" onClick="delTag(\'' + id + '\')" ></i> </label>'
      // <button style="cursor:pointer;padding-left:5px;"  onClick="delTag(\''+text+'\')">'+text+'<i style="cursor:pointer;padding-left:5px;"  class="remove el-icon-remove" @click="delTag(\''+this.Tags.tag_key+'='+this.Tags.tag_val+'\')"></i></button>';
      this.tagHtml = this.tagHtml.replace(delHtml, '')
      this.isShow = false
      this.bottonShow = true
      var div = document.getElementById('showTagsDiv2')
      div.innerHTML = this.tagHtml
    },
    getTagKeys() {
      // axios.get('/api/tagk')
      axiosservice({
        url: '/api/tagk',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.key_list.push({
                'id': index,
                'name': data[index]
              })
            }
            // console.log(this.key_list)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag数据失败!')
        })
    },
    getTagValues() {
      // axios.get('/api/tagv')
      axiosservice({
        url: '/api/tagv',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const data = res.data
            for (var index in data) {
              this.val_list.push({
                'id': index,
                'name': data[index]
              })
            }
            // console.log(this.val_list)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取tag值失败!')
        })
    },
    getMetricList() {
      axiosservice({
        url: '/api/metrics',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            const metricArrAll = res.data
            if (metricArrAll.length > 100) {
              this.metricArr = metricArrAll.slice(0, 100)// 多于100个只保留前100个,否则会卡慢
            } else {
              this.metricArr = metricArrAll
            }
            this.ruleForm.metric = metricArrAll[0] // 默认值取第一个
            this.getMetricTagTree()
            // console.log(metricArrAll)
            // setMetrics(res.data)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取metrics数据失败!')
        })
    },
    getAlertNameList() { // 用于判断警报名是否重复
      axiosservice({
        url: '/getalertname',
        method: 'get'
      })
        .then((res) => {
          if (res.status == 200) {
            // console.log(res.data.data)
            var temp = []
            this.alertNameArr = temp.concat(res.data.data)
            // console.log(this.alertNameArr)
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取警报数据失败!')
        })
    },
    addAlert(tempObj) {
      // const parameter = 'alertname=' + tempObj.alertname + '&time=' + tempObj.time + '&description=' + tempObj.description + '&metric=' + tempObj.metric +
      // '&intervalStr=' + tempObj.intervalStr + '&durationStr=' + tempObj.durationStr + '&content=' + tempObj.content + '&maximum=' + tempObj.maximum
      console.log(tempObj)
      // axios.get(this.baseURL + '/createalert?' + parameter)
      axiosservice.post('/createalert', JSON.stringify(tempObj), { headers: { 'Content-Type': 'text/plain;charset=UTF-8' }})
        .then((res) => {
          if (res.status == 200) {
            // this.alertNameArr = res.data.data.alertname
            console.log('添加成功')
            this.$emit('addAlert')// 子组件可以使用 $emit 触发父组件的自定义事件。
            this.getAlertNameList()
          }
        })
        .catch((error) => {
          console.log(error)
          this.$message.error('获取警报数据失败!')
        })
    },
    includeName() {
      if (this.alertNameArr.includes(this.ruleForm.alertname)) {
        this.$message({
          message: '该警报已存在，警报名不可重复',
          type: 'warning'
        })
        return false
      }
      return true
    },
    submitAdd() {
      this.$refs['form'].validate((valid) => {
        if (valid && this.includeName()) {
          const tempObj = {
            alertname: this.ruleForm.alertname,
            interval: this.ruleForm.intervalNum + this.ruleForm.intervalStr,
            duration: this.ruleForm.durationNum + this.ruleForm.durationStr,
            description: this.ruleForm.description,
            content: this.ruleForm.content,
            state: this.ruleForm.state,
            level: this.ruleForm.level,
            condition: {
              index: this.ruleForm.metric + '&' + this.Form.tag,
              function: this.ruleForm.function,
              more: this.ruleForm.more,
              less: this.ruleForm.less
            }
          }
          if (this.Form.tag == '') {
            tempObj.condition['index'] = this.ruleForm.metric
          } else {
            tempObj.condition['index'] = this.ruleForm.metric + '&' + this.Form.tag.replace(/=/g, ':')
            console.log(this.Form.tag.replace(/=/g, ':'))
          }
          console.log('tempObj')
          if (this.ruleForm.more + this.ruleForm.less) {
            this.addAlert(tempObj)
          } else {
            console.log('报警条件至少填一个边界值')
            this.$message({
              message: '报警条件至少填一个边界值',
              type: 'warning'
            })
          }
          // this.addAlert(tempObj).then(() => {
          //   this.$emit('addAlert')// 子组件可以使用 $emit 触发父组件的自定义事件。
          // }).catch(err => console.log(err))
        } else {
          if (!valid) {
            this.$message({
              message: '请填写必填项',
              type: 'warning'
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
@charset "UTF-8";
.formCol{
  height: 40px;
  line-height: 40px;
/* background-color:#e8e8e8; */
}
.tagLabel{
  padding-left: 10px;
  text-align: left;
  float:left;
}
label{
  font-size: 14px
}
.tagSelect2{
  width: 100px;

}
.tagDiv2{
  height: 40px;
  line-height: 40px;
  float:left;
  margin-right: 10px;
}

</style>
